package com.hgd.security.evp.biz.biz;

import com.alibaba.fastjson.JSONObject;
import com.hgd.security.evp.biz.entity.EvpElement;
import com.hgd.security.evp.biz.entity.EvpMenu;
import com.hgd.security.evp.biz.entity.EResourceAuthority;
import com.hgd.security.evp.biz.mapper.EvpResourceAuthorityMapper;
import com.hgd.security.evp.biz.vo.EResourceAuthorityVo;
import com.hgd.security.evp.biz.vo.MenuTree;
import com.hgd.security.evp.common.biz.BusinessBiz;
import com.hgd.security.evp.common.context.CurrentContext;
import com.hgd.security.evp.common.util.EmptyUtil;
import com.hgd.security.evp.common.util.ObjectResultResponse;
import com.hgd.security.evp.common.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

/**
 * @author By Shang
 * @version 2019-01-01 22:49:10
 */
@Service
public class EResourceAuthorityBiz extends BusinessBiz<EvpResourceAuthorityMapper, EResourceAuthority> {
	
	@Autowired
	private EvpMenuBiz menuBiz;

	@Autowired
	private EvpElementBiz evpElementBiz;
	
    @Transactional
    public ObjectResultResponse<Void> addAuthorityMenu(String authorityId, String menuId) {
        ObjectResultResponse<Void> restResult=new ObjectResultResponse<>();

        /*
         * menuId传后台的是一组ID，用逗号隔开
         */
        if(StringUtil.isBlank(authorityId)){
            restResult.setStatus(400);
            restResult.setMessage("请指定权限");
            return restResult;
        }

        if(StringUtil.isBlank(menuId)){
            restResult.setStatus(400);
            restResult.setMessage("请指定待分配的菜单");
        }

        List<String> menuIdList= Arrays.asList(StringUtil.split(menuId, ","));
        List<EvpMenu> menuList = menuBiz.getListByIds(StringUtil.join(menuIdList, ","));

        if(EmptyUtil.isEmpty(menuList)){
            restResult.setStatus(400);
            restResult.setMessage("未找到相应权限，请重试。");
            return restResult;
        }

        List<EvpMenu> allEmenu = menuBiz.getAllEmenu();

        // 待进行插入操作的对象集合
        Set<EResourceAuthority> raToInsert=new HashSet<>();

        if (EmptyUtil.isNotEmpty(allEmenu)) {
            // 递归查找父菜单
            for (EvpMenu tmpMenu : menuList) {
                recursiveBindParentMenu(tmpMenu, authorityId, allEmenu, raToInsert);
            }
        }

        /*
         * 将原权限下的菜单全删除
         * 将新菜单插入
         */
        deleteByAuthority(authorityId);
        this.mapper.insertList(raToInsert);

        restResult.setMessage("添加成功");
        restResult.setStatus(200);
        return restResult;
    }

    private void deleteByAuthority(String authorityId) {
        Example example=new Example(EResourceAuthority.class);
        example.createCriteria().andEqualTo("authorityId",authorityId);

        this.mapper.deleteByExample(example);
    }

    private void recursiveBindParentMenu(EvpMenu tmpMenu,String authorityId, List<EvpMenu> allEmenu, Set<EResourceAuthority> raToInsert) {
        EResourceAuthority eResourceAuthority=new EResourceAuthority();
        eResourceAuthority.setAuthorityId(authorityId);
        eResourceAuthority.setAuthorityType(EResourceAuthorityVo.AUTHORITY_TYPE_GROUP);
        eResourceAuthority.setResourceId(String.valueOf(tmpMenu.getId()));
        eResourceAuthority.setResourceType(EResourceAuthorityVo.RESOURCE_TYPE_MENU);
        eResourceAuthority.setCrtUserId(Integer.valueOf(CurrentContext.getUserId()));
        eResourceAuthority.setCrtUserName(CurrentContext.getUserName());
        eResourceAuthority.setCrtTime(new Date());
        eResourceAuthority.setParentId(-1);

        raToInsert.add(eResourceAuthority);

        allEmenu.forEach(menu->{
            if(!tmpMenu.getParentId().equals(-1)&&tmpMenu.getParentId().equals(menu.getId())){
                // 说明menu是tmp的父节点
                recursiveBindParentMenu(menu, authorityId, allEmenu, raToInsert);
            }
        });
    }

    public ObjectResultResponse<Void> addAuthorityButton(String authorityId, String elementId) {
        ObjectResultResponse<Void> result=new ObjectResultResponse<>();

        EResourceAuthority eResourceAuthority=new EResourceAuthority();
        eResourceAuthority.setAuthorityId(authorityId);
        eResourceAuthority.setAuthorityType(EResourceAuthorityVo.AUTHORITY_TYPE_GROUP);
        eResourceAuthority.setResourceId(elementId);
        eResourceAuthority.setResourceType(EResourceAuthorityVo.RESOURCE_TYPE_BUTTON);
        eResourceAuthority.setParentId(-1);

        this.insertSelectiveBindCrt(eResourceAuthority);
        result.setStatus(200);
        result.setMessage("添加按钮权限成功");
        return result;
    }

    public ObjectResultResponse<Void> updateAuthority(EResourceAuthority eResourceAuthority) {
        ObjectResultResponse<Void> result=new ObjectResultResponse<>();
        this.updateSelectiveByIdBindUpd(eResourceAuthority);
        result.setStatus(200);
        result.setMessage("更新权限成功");
        return result;
    }

    public ObjectResultResponse<Void> delAuthorityMenu(String ids) {
        ObjectResultResponse<Void> result=new ObjectResultResponse<>();

        if(StringUtil.isBlank(ids)){
            result.setStatus(400);
            result.setMessage("请指待删除记录ID");
            return result;
        }

        for(String id:StringUtil.split(ids)){
            this.deleteById(id);
        }
        result.setStatus(200);
        result.setMessage("删除菜单权限成功");
        return result;
    }

    public ObjectResultResponse<Void> delAuthorityButton(String ids) {
        ObjectResultResponse<Void> result=new ObjectResultResponse<>();

        if(StringUtil.isBlank(ids)){
            result.setStatus(400);
            result.setMessage("请指待删除记录ID");
            return result;
        }

        for(String id:StringUtil.split(ids)){
            this.deleteById(id);
        }
        result.setStatus(200);
        result.setMessage("删除菜按钮限成功");
        return result;
    }

	private List<MenuTree> getAuthorityMenu() {
		return menuBiz.getAuthorityMenu(Integer.valueOf(CurrentContext.getUserId()));
	}

	private List<EvpElement> getAuthorityButton() {
		return evpElementBiz.getAuthorityButton(CurrentContext.getUserId());
	}
	
	public JSONObject getAuthorityForUser() {
		List<EvpElement> authorityButton = getAuthorityButton();
		List<MenuTree> authorityMenu = getAuthorityMenu();
		
		JSONObject resultJObj=new JSONObject();
		resultJObj.put("menu", authorityMenu);
		resultJObj.put("button", authorityButton);
		return resultJObj;
	}
}